//
//  ViewController.m
//  EasyCrashLocation
//
//  Created by David on 15/6/30.
//  Copyright (c) 2015年 1school. All rights reserved.
//

#import "ViewController.h"

@implementation ViewController
{
    __weak IBOutlet NSTextField *filePathLB;
    __weak IBOutlet NSComboBox *archCB;
    
    __weak IBOutlet NSTextField *addrTF;
    __weak IBOutlet NSTextField *loadAddrTF;
    __weak IBOutlet NSTextField *offsetAddrTF;
    __weak IBOutlet NSTextField *resultLB;
    
    NSURL *fileUrl;
}

- (void)viewDidLoad {
    [super viewDidLoad];

    // Do any additional setup after loading the view.
}

- (void)setRepresentedObject:(id)representedObject {
    [super setRepresentedObject:representedObject];

    // Update the view, if already loaded.
}

#pragma mark - action
// 选文件
- (IBAction)onSelectFileBtnClick:(NSButton *)sender {
    NSOpenPanel *panel = [NSOpenPanel openPanel];
    panel.allowedFileTypes = @[/*@"xcarchive",*/ @"app"];
    [panel beginWithCompletionHandler:^(NSInteger result) {
        fileUrl = [[panel URLs] firstObject];
        if (fileUrl) {
            filePathLB.stringValue = [fileUrl absoluteString];
        }
    }];
}

// 清空
- (IBAction)onClearBtnClick:(NSButton *)sender {
    [addrTF setStringValue:@""];
    [loadAddrTF setStringValue:@""];
    [offsetAddrTF setStringValue:@""];
    [resultLB setStringValue:@""];
}

// 转换
- (IBAction)onTransformBtnClick:(NSButton *)sender {
    if ([self canCaculate]) {
        [self excuteCommand];
    }
}

// 计算出全部的三个空
- (BOOL)canCaculate
{
    NSString *addr = [addrTF stringValue];
    NSString *loadAddr = [loadAddrTF stringValue];
    NSString *offsetAddr = [offsetAddrTF stringValue];
    
    long long count = 0;
    if (addr.length != 0) {
        count ++ ;
    }
    if (loadAddr.length != 0) {
        count ++ ;
    }
    if (offsetAddr.length != 0) {
        count ++ ;
    }
    if (count < 2) {
        [self alert:@"至少填两个地址"];
        return NO;
    }
    
    // addr - loadAddr = hex(offsetAddr)
    if (addr.length == 0) {
        long long decAddr = [self numberFromHexString:loadAddr] + [offsetAddr longLongValue];
        addrTF.stringValue = [self hexStringFromString:[NSString stringWithFormat:@"%lld", decAddr]];
    } else if (loadAddr.length == 0) {
        long long decLoadAddr = [self numberFromHexString:addr] - [offsetAddr longLongValue];
        loadAddrTF.stringValue = [self hexStringFromString:[NSString stringWithFormat:@"%lld", decLoadAddr]];
    } else if (offsetAddr.length == 0) {
        long long decOffsetAddr = [self numberFromHexString:addr] - [self numberFromHexString:loadAddr];
        offsetAddrTF.stringValue = [NSString stringWithFormat:@"%lld", decOffsetAddr];
    } else {
        
    }
    
    if (!fileUrl) {
        [self alert:@"请选择app文件"];
        return NO;
    }
    
    return YES;
}

- (void)alert:(NSString *)msg
{
    NSAlert *alert = [[NSAlert alloc] init];
    alert.messageText = msg;
    [alert beginSheetModalForWindow:self.view.window completionHandler:^(NSModalResponse returnCode) {
        
    }];
}

// TODO:执行命令
- (void)excuteCommand
{
    NSString *filePath = [fileUrl path];
    NSArray *pathComponents = [[filePath stringByDeletingPathExtension] pathComponents];
    NSString *appName = [pathComponents objectAtIndex:pathComponents.count-1];
    NSString *addr = [addrTF stringValue];
    NSString *loadAddr = [loadAddrTF stringValue];
    
    // atos -o 1School.app/1School -l 0x82000 0x000cc70d
    NSString *o = [NSString stringWithFormat:@"%@/%@", filePath, appName];
    [self runScript:@"/usr/bin/atos" arguments:@[@"-o", o, @"-l", loadAddr, addr]];
}

-(void)runScript:(NSString*)script arguments:(NSArray *)arguments
{
    NSTask *task;
    task = [[NSTask alloc] init];
    [task setLaunchPath: script];
    
    [task setArguments: arguments];
    
    NSPipe *pipe;
    pipe = [NSPipe pipe];
    [task setStandardOutput: pipe];
    [task setStandardError: pipe];
    
    [task launch];
//    [task waitUntilExit];
    
    NSFileHandle *file;
    file = [pipe fileHandleForReading];
    
    NSData *data;
    data = [file readDataToEndOfFile];
    [file closeFile];
    
    NSString *string;
    string = [[NSString alloc] initWithData: data encoding: NSUTF8StringEncoding];
    
    resultLB.stringValue = string;
}

#pragma mark - 工具方法
- (NSString *)stringFromHexString:(NSString *)hexString
{
    hexString = [hexString lowercaseString];
    NSScanner * scanner = [[NSScanner alloc] initWithString:hexString];
    unsigned long long value = 0;
    BOOL result = [scanner scanHexLongLong:&value];
    if (result) {
        NSString *unicodeString = [NSString stringWithFormat:@"%lld", value];
        return unicodeString;
    } else {
        return @"";
    }
}

- (NSString *)hexStringFromString:(NSString *)string{
    NSString *hexStr = [NSString stringWithFormat:@"0x%llx", [string longLongValue]];
    return hexStr;
}

- (long long)numberFromHexString:(NSString *)hexString
{
    return [[self stringFromHexString:hexString] longLongValue];
}

@end
